import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:mdict_flutter_plugin/mdict_flutter_plugin.dart';
import 'package:mdict_flutter_plugin_example/utils/assets.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:mdict_flutter_plugin_example/utils/path.dart';
import 'package:audioplayers/audioplayers.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _mdictFlutterPlugin = MdictFlutterPlugin();
  late String _kxPath;
  late String _yuPath;
  late String _njPath;
  String _result = "";
  InAppWebViewController? _controller;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    const kxAssetsPath = 'assets/kx.mdx';
    _kxPath = await AssetsUtils.copyAssets2local(kxAssetsPath, kxAssetsPath);

    const yuAssetsPath = 'assets/yu.mdx';
    _yuPath = await AssetsUtils.copyAssets2local(yuAssetsPath, yuAssetsPath);
    const yuMddAssetsPath = 'assets/yu.mdd';
    await AssetsUtils.copyAssets2local(yuMddAssetsPath, yuMddAssetsPath);

    const njAssetsPath = 'assets/nj.mdx';
    _njPath = await AssetsUtils.copyAssets2local(njAssetsPath, njAssetsPath);
    const njMddAssetsPath = 'assets/nj.mdd';
    await AssetsUtils.copyAssets2local(njMddAssetsPath, njMddAssetsPath);


    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _mdictFlutterPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  _loadResult() async {
    final temp = '''
      <html lang="zh">
                <head>
                  <meta charset="utf-8">
                  <meta name="viewport" content="initial-scale=1,maximum-scale=5,user-scalable=yes,width=device-width">
                </head>
      <body>
        $_result
      </body>
     </html>
    ''';
    final x = await PathUtils.localDirectory + '/temp.html';
    await File(x).writeAsString(temp);

    _controller?.loadUrl(urlRequest: URLRequest(url: WebUri('file://$x')));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(children: [
            Text('Running on: $_platformVersion\n'),
            Row(children: [
              Text("kx: "),
              Expanded(child: TextField(onChanged: (v) async {
                int? count = await _mdictFlutterPlugin.getSizeMdict(_kxPath);
                print('......................kxcount:${count??0}');
                String? name = await _mdictFlutterPlugin.getNameMdict(_kxPath);
                print('......................kxName:${name??0}');
                _result = await _mdictFlutterPlugin.lookforMdict(_kxPath, v) ?? '';
                _loadResult();
              },)),


            ],),
            Row(children: [
              Text("yu: "),
              Expanded(child: TextField(onChanged: (v) async {
                _result = await _mdictFlutterPlugin.lookforMdict(_yuPath, v.trim()) ?? '';
                _loadResult();
              },)),

          ],),
          Row(children: [
            Text("nj: "),
            Expanded(child: TextField(onChanged: (v) async {
              int? count = await _mdictFlutterPlugin.getSizeMdict(_njPath);
              print('......................nj:${count??0}');

              String? name = await _mdictFlutterPlugin.getNameMdict(_njPath);
              print('......................njName:${name??0}');
              _result = await _mdictFlutterPlugin.lookforMdict(_njPath, v.trim()) ?? '';
              _loadResult();
            },))]),
      Expanded(child: InAppWebView(

        initialSettings: InAppWebViewSettings(
            transparentBackground: true,
            javaScriptCanOpenWindowsAutomatically: true,
            allowBackgroundAudioPlaying: true,
        ),
        onWebViewCreated: (InAppWebViewController controller) {
          _controller = controller;
        },

        shouldOverrideUrlLoading: (controller, navigationAction) async {
          var scheme = navigationAction.request.url?.scheme;
          print("scheme: $scheme");
          if (scheme == 'sound') {
            final path = navigationAction.request.url?.host.replaceAll('/', '\\');
            final data = await _mdictFlutterPlugin.getResourceMdict(_njPath, '\\${path}');
            print('$path: len:${data?.length ?? 0}');
            if (data != null) {
              final audioPlayer = AudioPlayer();
              await audioPlayer.setSourceBytes(data);
              await audioPlayer.resume();
            }

            return NavigationActionPolicy.CANCEL;
          }
          else if (scheme == 'entry') {
            return NavigationActionPolicy.CANCEL;
          }
          return NavigationActionPolicy.ALLOW;
        },

        shouldInterceptRequest: (controller, request) async {
          var url = request.url.toString();
          try {
            print('......url: $url');
            final pathPre = 'file://${await PathUtils.localDirectory}/';
            String assetsPath = url.substring(pathPre.length);
            final data = await _mdictFlutterPlugin.getResourceMdict(_njPath, '\\$assetsPath');
            print('$assetsPath: len:${data?.length ?? 0}');
            if (data != null) {
              await File('${await PathUtils.localDirectory}/$assetsPath').writeAsBytes(data);
            }
          } catch (e) {
            return null;
          }
        },
      )),
            Text("cc")
        ]),
    ))
    );
  }
}
